# -*- coding: utf-8 -*-
"""
Created on Fri Apr  5 10:50:16 2019

@author: AINIVERSHERRY
"""

data = pd.read_csv(r'G:\Python_Files\loans_2018q1_feature.csv')

#X为特征变量，y为标签变量
X = data.iloc[:, :9]
y = data.iloc[:, 9]

from sklearn.metrics import roc_auc_score
from sklearn.metrics import classification_report
from sklearn.metrics import accuracy_score as asc
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from imblearn.over_sampling import SMOTE
import warnings
warnings.filterwarnings('ignore')  


#划分数据集
X_train, X_test, y_train, y_test = train_test_split(X, y, \
                                            test_size = 0.3, random_state = 0)

#构建参数组合，训练调优
param_grid = {'C': [0.01, 0.1, 1, 10, 100, 1000,], 'penalty': ['l1', 'l2']}
grid_search = GridSearchCV(LogisticRegression(), param_grid, cv = 5)
grid_search.fit(X_train, y_train)
grid_search.best_params_

#测试集上测试
y_pred = grid_search.predict(X_test)

print('测试集上的准确率为：{: .2%}'.format(asc(y_test, y_pred)))
print('分类结果报告如下：')
print(classification_report(y_test, y_pred))
print('模型AUC值为：{: .4f}'.format(roc_auc_score(y_test, y_pred)))

#运用SMOTE算法实现数据集的平衡
over_samples_X, over_samples_y = SMOTE(random_state = 1234).fit_sample(X_train, y_train)
os_X_test, os_y_test = SMOTE(random_state = 1234).fit_sample(X_test, y_test)

#构建参数组合，训练调优
param_grid = {'C': [0.01, 0.1, 1, 10, 100, 1000,], 'penalty': ['l1', 'l2']}
gs = GridSearchCV(LogisticRegression(), param_grid, cv = 5)
gs.fit(over_samples_X, over_samples_y)
gs.best_params_
gs.best_score_  #模型在训练集上的准确率

#输出模型在训练集上的准确率和分类报告
gs.score(os_X_test, os_y_test)

os_y_pred = grid_search.predict(over_samples_X)

print('分类结果报告如下：')
print(classification_report(over_samples_y, os_y_pred))
print('SMOTE过采样后，模型AUC值为：{: .4f}'.format(roc_auc_score(over_samples_y, os_y_pred)))

#绘制ROC曲线
def auc_curve(y,prob):
    fpr,tpr,threshold = roc_curve(y,prob) ###计算真正率和假正率
    roc_auc = auc(fpr,tpr) ###计算auc的值
 
    plt.figure()
    lw = 2
    plt.figure(figsize=(10,10))
    plt.plot(fpr, tpr, color='darkorange',
             lw=lw, label='ROC curve (area = %0.3f)' % roc_auc) ###假正率为横坐标，真正率为纵坐标做曲线
    plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
    plt.xlim([0.0, 1.0])
    plt.ylim([0.0, 1.05])
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.title('Receiver operating characteristic example')
    plt.legend(loc="lower right")
 
    plt.show()

auc_curve(over_samples_y, os_y_pred)

